//
//  TKIMAddressBookHelper.m
//  TKIM_首创
//
//  Created by macpro on 15/12/9.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMAddressBookHelper.h"
#import "TKIMContactsGroup.h"
#import <AddressBook/AddressBook.h>

@implementation TKIMAddressBookHelper

/**
 *  申请访问用户的通讯录
 *
 *  @return 是否允许
 */
+(BOOL)addressBookIsAuthorized
{
    BOOL authorizedStatus = NO;
    if (ABAddressBookGetAuthorizationStatus()==kABAuthorizationStatusNotDetermined) {
        __block BOOL accessGranted = NO;
        //创建通讯簿的引用
        ABAddressBookRef addressBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error){
            //greanted为YES是表示用户允许，否则为不允许
            accessGranted = granted;
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        CFRelease(addressBook);
        authorizedStatus = accessGranted;
    }else if(ABAddressBookGetAuthorizationStatus()==kABAuthorizationStatusAuthorized){
        authorizedStatus = YES;
    }else{
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"暂无权限访问您的通讯录，请在手机系统设置中允许访问通讯录" delegate:nil cancelButtonTitle:@"知道了~" otherButtonTitles:nil, nil];
        [alertView show];
        authorizedStatus = NO;
    }
    return authorizedStatus;
}

/**
 *  获取手机通讯录所有的联系人,(储存TKIMContact对象)
 *
 *  @return 未分组的所有联系人
 */
+(NSMutableArray *)getAllContactsFromAddressBook
{
       NSMutableArray * contactsArray = [NSMutableArray array];
        //新建一个通讯录类
        ABAddressBookRef addressBooks =  ABAddressBookCreateWithOptions(NULL, NULL);
        CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
        //通讯录中人数
        CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
        //循环，获取每个人的个人信息
        for (NSInteger i = 0; i < nPeople; i++)
        {
            //新建一个addressBook model类
            TKIMContact *contact = [[TKIMContact alloc] init];
            //获取个人
            ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
            //获取个人名字
            CFTypeRef abName=ABRecordCopyValue(person, kABPersonFirstNameProperty);
            NSString *nameString = (__bridge NSString *)abName;
            CFTypeRef abLastName=ABRecordCopyValue(person, kABPersonLastNameProperty);
            NSString *lastName = (__bridge NSString *)abLastName;
            CFStringRef abFullName = ABRecordCopyCompositeName(person);
            NSString *fullName = (__bridge NSString *)abFullName;
            if (fullName != nil) {
                nameString = fullName;
            } else {
                if (lastName != nil)
                {
                    nameString = [NSString stringWithFormat:@"%@%@", nameString, lastName];
                }
            }
            //联系人头像
            CFDataRef abImageData = (ABPersonCopyImageDataWithFormat(person,kABPersonImageFormatThumbnail));
            NSData * imageData = (__bridge NSData *)abImageData;
            UIImage * image = [[UIImage alloc] initWithData:imageData];
            
            CFTypeRef abNickname = ABRecordCopyValue(person, kABPersonNicknameProperty);
            NSString *nickname = (__bridge NSString *)abNickname;
            
            contact.name = nameString;
            contact.recordID = (int)ABRecordGetRecordID(person);
            contact.nickname = nickname;
            //将中文转成全大写拼音

            if (contact.name.length>0) {
                NSString * enName = [[TKIMStringHelper parseCnToEn:contact.name] uppercaseString];
                contact.pinyinName = enName;
                NSString * firstCharacter = [[enName substringToIndex:1] uppercaseString];
                unichar character=[firstCharacter characterAtIndex:0];
                //将首字母为特殊符号或名字为空的列为"#"
                if (character<'A'||character>'Z') {
                    firstCharacter = @"#";
                }
                contact.firstLetter = firstCharacter;
            }else{ //name为空时 也将首字母置为"#"
                contact.firstLetter = @"#";
            }
            contact.image = image;
            
            ABPropertyID multiProperties[] = {
                kABPersonPhoneProperty,//电话
                kABPersonEmailProperty,//email
                kABPersonAddressProperty,//住址
            };
            NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
            for (NSInteger j = 0; j < multiPropertiesTotal; j++) {
                ABPropertyID property = multiProperties[j];
                ABMultiValueRef valuesRef = ABRecordCopyValue(person, property);
                NSInteger valuesCount = 0;
                if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);
                
                if (valuesCount == 0) {
                    CFRelease(valuesRef);
                    continue;
                }
                //获取电话号码和email
                for (NSInteger k = 0; k < valuesCount; k++) {
                    CFTypeRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);
                    switch (j) {
                        case 0: {// Phone number
                            contact.tel = (__bridge NSString*)value;
                            break;
                        }
                        case 1: {// Email
                            contact.email = (__bridge NSString*)value;
                            break;
                        }
                        case 2: {// 住址
                            contact.address = (__bridge NSString*)value;
                            break;
                        }
                    }
                    CFRelease(value);
                }
                CFRelease(valuesRef);
            }
            
            //将个人信息添加到数组中，循环完成后contacts中包含所有联系人的信息
            [contactsArray addObject:contact];
            
            if (abName) CFRelease(abName);
            if (abLastName) CFRelease(abLastName);
            if (abFullName) CFRelease(abFullName);
            if (abImageData) CFRelease(abImageData);
            if (abNickname) CFRelease(abNickname);
        }
    if (addressBooks) CFRelease(addressBooks);
    if (allPeople) CFRelease(allPeople);
    
    return contactsArray;
}
/**
 *  获取按字母顺序分组后的所有联系人，(储存TKIMContactsGroup对象)
 */
+(NSArray *)getAllContactsGroupFromAddressBook
{
    return [self sortGroupByFirstLetterWithAllContacts:[self getAllContactsFromAddressBook]];
}

//对所有的联系人按首字母进行分组
+(NSArray *)sortGroupByFirstLetterWithAllContacts:(NSArray *)contactsArr
{
    NSMutableArray * contactsGroupArray = [NSMutableArray array];
    
    NSSortDescriptor * sortDes = [NSSortDescriptor sortDescriptorWithKey:@"firstLetter" ascending:YES];
    NSMutableArray * sortContacts=[NSMutableArray arrayWithArray:[contactsArr sortedArrayUsingDescriptors:@[sortDes]]];
    //将拼音首字母相同的存在一起
    for (NSInteger i = 0; i<sortContacts.count; i++) {
        
        TKIMContactsGroup * group = [[TKIMContactsGroup alloc] init];
        TKIMContact * contact1 = sortContacts[i];
        group.groupLetter = contact1.firstLetter;
        [group.contactsArr addObject:contact1];
        
        for (NSInteger j = i+1; j<sortContacts.count-1; j++) {
            TKIMContact * contact2 = sortContacts[j];
            if ([contact2.firstLetter isEqualToString:contact1.firstLetter]) {
                [group.contactsArr addObject:contact2];
                i=j+1;
            }else
            {
                i=j-1;
                break;
            }
        }
        [contactsGroupArray addObject:group];
    }
    //将第一组的"#"置在字母"Z"之后
    if (contactsGroupArray.count>0) {
        TKIMContactsGroup * group =contactsGroupArray[0];
        if ([group.groupLetter isEqualToString:@"#"]) {
            [contactsGroupArray addObject:group];
            [contactsGroupArray removeObjectAtIndex:0];
        }
    }
    return contactsGroupArray;
}


/**
 *  手机号码验证
 *
 *  @param mobileNumbel 传入的手机号码
 *
 *  @return 格式正确返回true  错误 返回fals
 */
+ (BOOL) isMobile:(NSString *)mobileNumbel{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}


/**
 *  @Author lpm, 16-04-13 11:04:13
 *
 *  @brief  将用户添加到通讯录
 *
 *  @param users
 *
 */
+(void)addToContacts:(NSMutableArray *)users  callBack:(void(^)(BOOL suc))callBack
{
    CFErrorRef error = NULL;
    //创建一个通讯录操作对象
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
                                             {
                                                 if (granted && !error)
                                                 {
                                                     for (TKIMContact *user in users)
                                                     {
                                                         @autoreleasepool
                                                         {
                                                             // 创建一条新的联系人纪录
                                                             ABRecordRef newRecord = ABPersonCreate();
                                                             
                                                             // 为新联系人记录添加属性值
                                                             ABRecordSetValue(newRecord,
                                                                              kABPersonFirstNameProperty,
                                                                              (__bridge CFTypeRef)user.name,
                                                                              &error);
                                                             //创建一个多值属性
                                                             ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
                                                             ABMultiValueAddValueAndLabel(multi,
                                                                                          (__bridge CFTypeRef)user.tel,
                                                                                          kABPersonPhoneMobileLabel,NULL);
                                                             
                                                             //将多值属性添加到记录
                                                             ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);
                                                             //添加记录到通讯录操作对象
                                                             ABAddressBookAddRecord(addressBook, newRecord, &error);
                                                             
                                                             CFRelease(newRecord);
                                                             CFRelease(multi);
                                                         }
                                                     }
                                                     //保存通讯录操作对象
                                                     ABAddressBookSave(addressBook, &error);
                                                     CFRelease(addressBook);
                                                     dispatch_im_main_async_safe(^{
                                                         if (error)
                                                         {
                                                             callBack(NO);
                                                         }
                                                         else
                                                         {
                                                             callBack(YES);
                                                         }
                                                     });
                                                 }
                                                 else
                                                 {
                                                     dispatch_im_main_async_safe((^{
                                                         callBack(NO);
                                                         UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"暂无权限访问您的通讯录，请在手机系统设置中允许访问通讯录" delegate:nil cancelButtonTitle:@"知道了~" otherButtonTitles:nil, nil];
                                                         [alertView show];
                                                     }));
                                                     
                                                 }
                                             });
}


/**
 *  @Author lpm, 16-04-13 12:04:18
 *
 *  @brief  弹出添加人到通讯录的编辑界面
 *
 *  @param contact
 *  @param ctrl
 */
+(void)addToContacts:(TKIMContact *)contact contentViewCtrl:(UIViewController<ABNewPersonViewControllerDelegate> *)ctrl avatar:(UIImage *)avatar isPush:(BOOL)push
{
    //创建添加联系人控制器
    ABNewPersonViewController *newPersonViewController = [[ABNewPersonViewController alloc] init];
    
    //创建一条记录
    ABRecordRef newPerson = ABPersonCreate();
    CFErrorRef error = NULL;
    
    NSString *lastName = @"";
    NSString *firstName = @"";
    if(contact.name.length)
    {
        lastName = [contact.name substringToIndex:1];
        firstName = [contact.name substringFromIndex:1];
    }
    //名
    ABRecordSetValue(newPerson,kABPersonFirstNameProperty,(__bridge CFTypeRef)firstName,&error);
    //姓
    ABRecordSetValue(newPerson,kABPersonLastNameProperty,(__bridge CFTypeRef)lastName,&error);
    
    //添加手机号属性
    ABMutableMultiValueRef multiValue = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
    multiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multiValue, (__bridge CFTypeRef)(contact.tel), kABPersonPhoneMainLabel, NULL);
    ABMultiValueAddValueAndLabel(multiValue, (__bridge CFTypeRef)contact.tel, kABPersonPhoneMobileLabel,NULL);
    
    //添加邮箱属性
    ABMutableMultiValueRef  mailValue = ABMultiValueCreateMutable(kABPersonEmailProperty);
    // 为工作的电子邮件添加label
    ABMultiValueAddValueAndLabel(mailValue , (__bridge  CFStringRef)contact.email,   (__bridge  CFStringRef)@"工作",  NULL);
    ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiValue , &error);
    ABRecordSetValue(newPerson, kABPersonEmailProperty, mailValue , &error);
    
    newPersonViewController.displayedPerson = newPerson;
    
    // 头像
    if (avatar) {
        NSData *data=UIImagePNGRepresentation([self getSubImage:avatar size:CGSizeMake(160, 160)]);
        ABPersonRemoveImageData(newPerson, NULL);
        CFDataRef cfData=CFDataCreate(NULL, [data bytes], [data length]);
        CFErrorRef *error;
        ABPersonSetImageData(newPerson, cfData, error);
    }
    
    // 设置代理
    newPersonViewController.newPersonViewDelegate = ctrl;
    if (push)
    {
        [ctrl.navigationController pushViewController:newPersonViewController animated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            newPersonViewController.navigationController.navigationBar.tintColor = [TKIMColorHelper stringToColor:@"#333333"];
        });
    }
    else
    {
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:newPersonViewController];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            newPersonViewController.navigationController.navigationBar.tintColor = [TKIMColorHelper stringToColor:@"#333333"];
        });
        [ctrl presentViewController:nav animated:YES completion:nil];
    }
}

//截取部分图像
+(UIImage*)getSubImage:(UIImage *)image size:(CGSize)size
{
//    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
//    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
//    
//    UIGraphicsBeginImageContext(smallBounds.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextDrawImage(context, smallBounds, subImageRef);
//    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
//    UIGraphicsEndImageContext();
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImage;
}

@end
